<?php
class OrderController extends BaseController
{
    // {$url}/order/clear
    public function clearAction()
    {
        // 清理超过10分钟未支付的订单
        $db = $this->mysql();

        $db->update('cecharge_order', [
            'status'     => 'error',
            'pay_list'   => '订单超时',
            'deletetime' => time(),
        ], [
            'createtime[<]'  => time() - 300,
            'paytime'        => 0,
            'status'         => 'wait',
            'balance'        => 0,
            'payment_amount' => 0,

        ]);

        $db->action(function ($database) {
            // 清理已扣除余额，未成功支付，订单
            $order = $database->select('cecharge_order', '*', [
                'createtime[<]'     => time() - 300,
                'paytime'           => 0,
                'status'            => 'wait',
                'balance[>=]'       => 0,
                'payment_amount[>]' => 0,
            ]);

            if (!empty($order)) {
                foreach ($order as $key => $value) {
                    if ($value['balance'] > 0) {
                        // 获取上一级用户信息
                        $account_balance = $database->get('user', 'account_balance', [
                            'user_number' => $value['user_number'],
                        ]);
                        // 加入资金变动明细
                        $database->insert('user_money_log', [
                            'order_number' => $value['order_number'],
                            'user_number'  => $value['user_number'],
                            'before'       => $account_balance,
                            'money'        => $value['balance'],
                            'after'        => $account_balance + $value['balance'],
                            'state'        => '订单超时退款',
                            'type'         => '退款',
                            'other'        => $value['user_number'],
                            'createtime'   => time(),
                        ]);
                        if ($database->id() < 1) {
                            dump_log('退款： ' . $value['order_number'] . ' 状态： 退款失败', 'cash_bonus_error.txt');
                            return false;
                        }

                        // 更新钱包数据
                        $res = $database->update('user', [
                            'account_balance[+]' => $value['balance'],
                            // 'withdrawals'        => $card_member,

                        ], ['user_number' => $value['user_number']]);
                        if ($res->rowCount() == 0) {
                            dump_log('退款： ' . $value['order_number'] . ' 状态： 更新用户金额失败', 'cash_bonus_error.txt');
                            return false;
                        }
                    }
                    $res = $database->update('cecharge_order', [
                        'status'     => 'error',
                        'pay_list'   => '订单超时',
                        'deletetime' => time(),
                    ], [
                        'order_number' => $value['order_number'],
                    ]);
                    if ($res->rowCount() == 0) {
                        dump_log('退款： ' . $value['order_number'] . ' 状态： 更新用户金额失败', 'cash_bonus_error.txt');
                        return false;
                    }
                    var_dump('订单：' . $value['order_number'] . ' 成功为' . $value['user_number'] . '退款' . $value['balance'] . '元');

                }
                return true;
            }

        });

        return false;
    }

    // {$url}/order/commit 订单提交
    public function commitAction()
    {
        // ignore_user_abort(true); // 设定关闭浏览器也执行程序
        set_time_limit(0); // 设定响应时间不限制，默认为30秒
        $db = $this->mysql();
        while (true) {
            $data = $db->select('cecharge_order', [
                'id', 'user_number', 'order_number', 'shop_info', 'payment_amount', 'recharge_amount', 'mobile',
            ], ['order_type' => 0, 'cecharge_type' => 'telephone_bill', 'paytime[>]' => 0, 'deletetime' => null, 'pay_list' => '已支付', 'cecharge_channel_id' => 0, 'status' => 'wait', 'LIMIT' => 30,
            ]);
            file_put_contents('test.txt', var_export($data, true) . PHP_EOL, FILE_APPEND);
            if ($data) {
                foreach ($data as $key => $value) {
                    $goods                         = json_decode($value['shop_info'], true);
                    $goods['cecharge_channel_ids'] = explode(',', $goods['cecharge_channel_ids']);
                    $count                         = count($goods['cecharge_channel_ids']);
                    foreach ($goods['cecharge_channel_ids'] as $k => $v) {
                        // 查询通道信息
                        $cecharge_channel = $db->get('cecharge_channel', [
                            'id', 'channel_name', 'channel_name_en', 'domain_name', 'configjson', 'callback_url',
                        ], [
                            'id'    => $v,
                            'state' => 'enable', 'deletetime' => null,
                            // 'id' => 3,
                        ]);
                        if (is_null($cecharge_channel)) {continue;}
                        // 提交申请
                        $cecharge_channel['order_number']    = $value['order_number'];
                        $cecharge_channel['recharge_amount'] = $value['recharge_amount'];
                        $cecharge_channel['mobile']          = $value['mobile'];
                        $obj                                 = new CechargeChannel\Channel();
                        $result                              = $obj->commit($cecharge_channel);
                        // $result['success'] = false;
                        if ($result['success'] == false) {
                            file_put_contents('commit_order.txt', date('Y-m-d H:i:s') . ' 订单号： ' . $value['order_number'] . '充值失败，使用通道： ' . var_export($result, true) . PHP_EOL, FILE_APPEND);
                            echo date('Y-m-d H:i:s') . ' 订单号： ' . $value['order_number'] . '充值失败，使用通道： <br>' . $v;
                            if ($k + 1 == $count) {
                                //充值任务失败
                                $db->update('cecharge_order', ['status' => 'error', 'cecharge_channel_id' => $cecharge_channel['id']], ['order_number' => $value['order_number']]);
                            }
                            continue;
                        }
                        if ($result['success'] == true) {
                            unset($result['success']);
                            $result['user_number'] = $value['user_number'];
                            $db->insert('cecharge_notify', $result);

                            $db->update('cecharge_order', ['order_type' => 1, 'cecharge_channel_id' => $cecharge_channel['id']], ['order_number' => $value['order_number']]);
                            echo date('Y-m-d H:i:s') . ' 订单号： ' . $value['order_number'] . '充值成功，使用通道： <br>' . $v;

                            break;
                        }
                    }
                }
            }
            sleep(1);
            // 设定定时任务终止条件
            if (file_exists('lock.txt')) {break;}
        }
        return false;
    }
    // {$url}/order/callbackMessage
    public function callbackMessageAction()
    {

    }

    // 将15天以前数据设置为历史订单
    public function clearOrderDataAction()
    {
        die();
        $time = strtotime(date('Y-m-d')) - 86400 * 15;
        $db   = $this->mysql();
        $i    = 30;
        echo '<Pre>';
        while ($i > 0) {
            $this->data = $db->select('aggregation_order', '*', [
                'createtime[<]' => $time,
                'LIMIT'         => 50,
            ]);
            if(!empty($this->data)){
                $data = $this->data;
                $this->data = [];
                foreach($data as $key => $value){
                    unset($value['id']);
                    if( $db->has('aggregation_history_order',['cloud_order_number'=>$value['cloud_order_number']])){
                         $db->delete('aggregation_order',['cloud_order_number'=>$value['cloud_order_number']]);
                        echo '111';
                   
                    }
                    $this->data[] = $value;
                }
               
                $db->action(function($database) {
     
                   
                    // unset($this->data['id']);
                    $database->insert('aggregation_history_order',$this->data);
                    // print_r($this->data);
                    // print_r($database->error());
                    // return false;
                    // die();
                    if($database->error()[0] != '00000'){
                  
                    print_r($database->error());
                        echo '添加失败';
                        return false;
                    }
                    $data = $this->data;
                
                    array_walk($this->data,function(&$value, $key){
                        $this->ids[] = $value['cloud_order_number'];
                    });
                    $database->delete('aggregation_order',['cloud_order_number'=>$this->ids]);
                    if($database->error()[0] != '00000'){
                        echo '删除失败';
                        return false;
                    }
                    $this->ids = [];
                    echo '同步成功';
                    return true;
                });
                $i = $i - 1;
            }else{
                $id = 0;
            }
            
        }
    }
}
